<script setup lang="ts">
import {ref, reactive, computed, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import ElectricalMaterialDialog from '@/views/baseInfo/electrical/electricalMaterialDialog/index.vue'
import {Plus, Delete, Select, Document, Search, Refresh} from '@element-plus/icons-vue'
// 项目类型
import {ProjectDocument, ProjectDocumentListParam} from '@/api/project/type'
// 获取项目api
import {getProjectDocumentListApi} from '@/api/project'
// 电控成本核价单  新增，编辑，获取详情api
import {
  getSoftwarePlanApi,
  submitCreateCostPricingPlanApi,
  submitUpdateCostPlan,
  getCostTemplateApi
} from '@/api/costPricingPlan'
// 电控成本单类型
import {additionalTableData, costPlan} from '@/api/costPricingPlan/type'
import ArchiveSelector from '@/components/common/ArchiveSelector.vue'
import {getListApi as getDictDataApi} from '@/api/sysDictData'
import {SysDictDataListParam} from '@/api/sysDictData/type'
// 引入vue-router
import {useRoute} from 'vue-router'
// 获取路由实例
const route = useRoute()
// 引入vue-router
import {useRouter} from 'vue-router'
// 获取路由实例
const router = useRouter()

// 查看模式状态
const isViewMode = computed(() => route.query.mode === 'view')
const pageTitle = computed(() => isViewMode.value ? '查看成本核价单' : '电控成本核价单')

// 项目选择器相关数据
const projectSelectorVisible = ref(false)
const selectedProject = ref<ProjectDocument | null>(null)
// 项目状态映射
const statusOptions = [
  {value: 0, label: '进行中'},
  {value: 1, label: '已完成'},
  {value: 2, label: '已暂停'},
  {value: 3, label: '已取消'},
]
// 项目选择器搜索字段配置
const projectSearchFields = [
  {label: '项目名称', prop: 'name', type: 'input' as const},
  {label: '项目编号', prop: 'code', type: 'input' as const},
  {label: '客户名称', prop: 'customer', type: 'input' as const},
  {
    label: '项目状态',
    prop: 'status',
    type: 'select' as const,
    options: statusOptions,
  },
]

// 项目选择器表格列配置
const projectTableColumns = [
  {prop: 'name', label: '项目名称', width: 250},
  {prop: 'code', label: '项目编号', width: 250},
  {prop: 'customer', label: '客户名称', width: 250},
  {prop: 'manager', label: '项目经理', width: 200},
]

// 获取项目列表数据的API方法
const getProjectList = async (params: any) => {
  try {
    // 构建查询参数
    const queryParams: ProjectDocumentListParam = {
      name: params.name,
      code: params.code,
      customer: params.customer,
      status: params.status,
      page: params.page || 1,
      limit: params.limit || 10,
    }

    // 调用项目列表API - 使用真实API
    return await getProjectDocumentListApi(queryParams)
  } catch (error) {
    console.error('获取项目列表失败:', error)
    return {data: {list: [], total: 0}}
  }
}

// 打开项目选择器
const openProjectSelector = () => {
  projectSelectorVisible.value = true
}

// 处理项目选择确认
const handleProjectSelect = (project: ProjectDocument) => {
  selectedProject.value = project
  console.log('选择的项目:', project)
  form.projectId = project.id
}

// 电控物料对话框引用
const electricalMaterialDialogRef = ref()

// 多选模式选中的物料列表
const selectedMaterials = ref<any[]>([])

// 是否使用多选模式
const isMultipleMode = ref(true)

// 物料系数加成选项
const materialCoefficientOptions = ref([{label: '采购价系数', value: '1.17'}])

// 表单信息
const form = reactive<costPlan>({
  id: null,
  projectId: undefined, // 项目id
  totalPrice: undefined, // 总价
  remark: '', // 备注说明
  docType: '输送系统', // 单据类型，默认为输送系统
  costDetailList: [], // 电控物料明细
  additionalTableData: [], // 自定义模版数据
  materialCoefficient: 1, // 物料系数加成，默认为1
})

/*
// 额外表格数据
const additionalTableData = ref<any[]>([])
*/

// 计算额外表格行的合计
const calculateAdditionalTotal = (row: any) => {
  // 特殊处理：非标工艺占比和非常规环境的合计 = 占比 * 物料总金额
  if (row.name === '非标工艺占比' || row.name === '非常规环境') {
    row.total = (row.ratio || 0) * (totalAmount.value+additionalMaterialTotalAmount.value);
  } else {
    // 其他项目按原计算方式：(单价1 + 单价2) * (1 + 所有溢价) * 数量
    const totalPremium = (row.premium || 0) + (row.premiumTwo || 0) + (row.premiumThree || 0) + (row.premiumFour || 0);
    row.total = (row.price + row.priceTwo) * (1 + totalPremium) * row.quantity
  }
  return row.total
}

// 初始化物料数量和总价
const initMaterialQuantity = (material: any) => {
  if (!material.quantity) {
    material.quantity = 1
  }
  calculateTotal(material)
}

// 计算单个物料的总价
const calculateTotal = (material: any) => {
  const price = material.price || 0
  const priceTwo = material.priceTwo || 0
  const premium = material.premium || 0
  const premiumTwo = material.premiumTwo || 0
  const premiumThree = material.premiumThree || 0
  const premiumFour = material.premiumFour || 0
  const quantity = material.quantity || 1
  const additionalContent = material.additionalContent || 0
  // 计算公式：总价 = (单价1*数量+单价2*总层数)*(1+溢价1+溢价2+溢价3+溢价4)
  material.totalPrice = (price * quantity + priceTwo * additionalContent) * (1 + premium + premiumTwo + premiumThree + premiumFour)
  return material.totalPrice
}

// 更新物料数量
const updateQuantity = (material: any, value: number) => {
  material.quantity = value || 0
  // 使用统一的计算逻辑
  calculateTotal(material)
}

// 打开多选模式对话框
const openMultipleSelectDialog = () => {
  isMultipleMode.value = true
  // 打开对话框前，确保物料选择器组件知道哪些物料已被选中
  electricalMaterialDialogRef.value.onShow(selectedMaterials.value)
}

// 多选模式下物料选择变化时的处理函数
const handleMaterialSelectionChange = (selection: any) => {
  // 获取当前选中的物料ID集合
  const selectedIds = selection.map((item: any) => item.id)
  // 从 form.costDetailList 中移除已取消勾选的物料
  form.costDetailList = form.costDetailList.filter((item: any) => {
    // 保留仍在选中状态的物料
    return selectedIds.includes(item.costMaterialId)
  })

  // 2. 更新 selectedMaterials
  selectedMaterials.value = selection

  // 3. 为每个选中的物料初始化数量和计算总价
  selectedMaterials.value.forEach((material) => {
    initMaterialQuantity(material)
  })

  // 4. 更新表格数据（添加新选中的物料）
  updateTableList()
}

// 更新表格数据列表
const updateTableList = () => {
  // 将选择的物料添加到表格数据中，避免重复
  selectedMaterials.value.forEach((material) => {
    if (
        !form.costDetailList.some((item: any) => item.costMaterialId === material.id)
    ) {
      form.costDetailList.push({
        costMaterialId: material.id,
        name: material.name,
        specification: material.specification,
        brand: material.brand,
        price: material.price || 0,
        priceTwo: material.priceTwo || 0,
        premium: material.premium || 0,
        premiumTwo: material.premiumTwo || 0,
        premiumThree: material.premiumThree || 0,
        premiumFour: material.premiumFour || 0,
        quantity: material.quantity || 1,
        additionalContent: 0, // 总层数/接驳口默认为0，后续可手动填写
        totalPrice: material.totalPrice || 0,
      })
    }
  })
}

// 确认多选完成时的处理函数
const confirmMaterialSelect = async () => {
  if (selectedMaterials.value.length === 0) {
    ElMessage.warning('请至少选择一个物料')
    return
  }

  ElMessage.success(`已选择 ${selectedMaterials.value.length} 个物料`)
  electricalMaterialDialogRef.value.onClose()

  // 更新表格数据
  updateTableList()

  // 这里可以进行后续处理，例如将选中的物料添加到表单中
  console.log('选中的物料列表:', selectedMaterials.value)
  // 重新获取模版
  //await getCostPlanTemplate(form.docType);
}

// 物料基础价格（未加成前）
const materialBaseAmount = computed(() => {
  return form.costDetailList.reduce(
      (sum: number, item: any) => sum + (item.totalPrice || 0),
      0
  )
})

// 物料计算总价（应用系数后）
const totalAmount = computed(() => {
  return materialBaseAmount.value * form.materialCoefficient
})

// 额外表格总价
const additionalTotalAmount = computed(() => {
  return form.additionalTableData.reduce(
      (sum: number, item: any) => sum + (item.total || 0),
      0
  )
})

// 额外物料数据（根据名称判断是否为服务类内容）
const additionalMaterialData = computed(() => {
  return form.additionalTableData.filter((item: any) => {
    // 服务类项目名称列表
    const serviceNames = ['图纸设计', '程序设计', '非标工艺占比', '非常规环境', '配盘', '安装', '陪调', '调试', '陪产', '现场安装','往返公里']
    // 如果name中包含服务类关键词，则不是物料
    const isService = serviceNames.some(serviceName => (item.name || '').includes(serviceName))
    return !isService
  })
})

// 额外内容数据（服务类项目）
const additionalContentData = computed(() => {
  return form.additionalTableData.filter((item: any) => {
    // 服务类项目名称列表
    const serviceNames = ['图纸设计', '程序设计', '非标工艺占比', '非常规环境', '配盘', '安装', '陪调', '调试', '陪产', '现场安装','往返公里']
    // 如果name中包含服务类关键词，则是服务内容
    const isService = serviceNames.some(serviceName => (item.name || '').includes(serviceName))
    return isService
  })
})

// 额外物料基础价格（未加成前）
const additionalMaterialBaseAmount = computed(() => {
  return additionalMaterialData.value.reduce(
      (sum: number, item: any) => sum + (item.total || 0),
      0
  )
})

// 额外物料总价（应用系数后）
const additionalMaterialTotalAmount = computed(() => {
  return additionalMaterialBaseAmount.value * form.materialCoefficient
})

// 额外内容总价
const additionalContentTotalAmount = computed(() => {
  return additionalContentData.value.reduce(
      (sum: number, item: any) => sum + (item.total || 0),
      0
  )
})

// 保存表单
const saveForm = async () => {
  if (!form.projectId) {
    ElMessage.warning('请选择项目')
    return
  }



  try {
    // 自动使用计算参考值作为总价

    // 判断是新增还是修改
    if (form.id) {
      // 修改
      await submitUpdateCostPlan(form)
      ElMessage.success('修改成功')
      resetForm()
    } else {
      // 新增
      await submitCreateCostPricingPlanApi(form)
      ElMessage.success('提交成功')
      resetForm()
    }
  } catch (error) {
    console.log(error)
  }
}

// 返回
const resetForm = () => {
  router.push(`/costPlan`)
}

// 页面加载状态
const loading = ref(false)

// 获取成本单详情数据
const getCostPlanDetail = async (id: string | number) => {
  try {
    loading.value = true
    const res = await getSoftwarePlanApi(id)
    if (res && res.data) {
      // 填充表单数据
      form.id = res.data.id
      form.projectId = res.data.projectId
      form.totalPrice = res.data.totalPrice
      form.remark = res.data.remark
      form.docType = res.data.docType || '输送系统' // 设置单据类型，如果没有则默认为输送系统
      form.materialCoefficient = res.data.materialCoefficient || 1 // 物料系数加成，默认为1

      // 清空现有物料列表
      form.costDetailList = []

      // 填充物料明细
      if (res.data.costDetailList && res.data.costDetailList.length > 0) {
        form.costDetailList = res.data.costDetailList.map((item: any) => {
          // 计算总价 - 使用原始公式：(单价1*数量+单价2*总层数)*(1+溢价1+溢价2+溢价3+溢价4)
          const totalPrice =
              ((item.price || 0) * (item.quantity || 1) + (item.priceTwo || 0) * (item.additionalContent || 0)) * (1 + (item.premium || 0) + (item.premiumTwo || 0) + (item.premiumThree || 0) + (item.premiumFour || 0))
          // 根据是否有costMaterialId区分物料档案项和自定义项
          return {
            ...item,
            premiumTwo: item.premiumTwo || 0,
            premiumThree: item.premiumThree || 0,
            premiumFour: item.premiumFour || 0,
            totalPrice: totalPrice,
          }
        })

        // 如果有物料档案中的项，将它们添加到selectedMaterials中
        const archiveMaterials = res.data.costDetailList
            .filter((item: any) => item.costMaterialId)
            .map((item: any) => ({
              id: item.costMaterialId,
              name: item.name,
              specification: item.specification,
              brand: item.brand,
              price: item.price,
              premium: item.premium,
              premiumTwo: item.premiumTwo,
              premiumThree: item.premiumThree,
              premiumFour: item.premiumFour,
              quantity: item.quantity,
            }))

        if (archiveMaterials.length > 0) {
          selectedMaterials.value = archiveMaterials
        }

        // 额外模版数据
        if (res.data.additionalTableData.length > 0) {
          form.additionalTableData = res.data.additionalTableData
        }
      }
      // 获取项目信息
      if (res.data.projectId) {
        selectedProject.value = {
          id: res.data.projectId,
          name: res.data.projectName || '项目信息',
          // 其他项目属性...
        } as ProjectDocument
      }
    }
  } catch (error) {
    console.error('获取成本单详情失败:', error)
    ElMessage.error('获取成本单详情失败')
  } finally {
    loading.value = false
  }
}


// 修改单据类型
const changeDocType = async (type: string) => {
  try {
    if(form.costDetailList.length === 0) {
      ElMessage.warning('请先添加物料明细')
      return
    }
    loading.value = true
    form.additionalTableData= []
    const res = await getCostTemplateApi({
      type,
      costDetailList: form.costDetailList,
      additionalTableData: form.additionalTableData
    })
    if (res && res.data) {
      form.additionalTableData = res.data
    }
  } catch (error) {
    console.error('获取成本单详情失败:', error)
    ElMessage.error('获取成本单详情失败')
  } finally {
    loading.value = false
  }
}

// 获取根据分类查询对的固定项表格
const getCostPlanTemplate = async (type: string) => {
  try {
    if(form.costDetailList.length === 0) {
      ElMessage.warning('请先添加物料明细')
      return
    }
    loading.value = true
    const res = await getCostTemplateApi({
      type,
      costDetailList: form.costDetailList,
      additionalTableData: form.additionalTableData
    })
    if (res && res.data) {
      form.additionalTableData = res.data
    }
  } catch (error) {
    console.error('获取成本单详情失败:', error)
    ElMessage.error('获取成本单详情失败')
  } finally {
    loading.value = false
  }
}

// 获取物料系数加成选项
const getMaterialCoefficientOptions = async () => {
  try {
    const queryParams: SysDictDataListParam = {
      dictType: 'software_purchase_price',
      page: 1,
      limit: 10,
    }
    const response = await getDictDataApi(queryParams)
    const dataList = response.data.list
    materialCoefficientOptions.value = dataList.map((item: any) => ({
      label: item.dictLabel,
      value: item.dictValue,
    }))
  } catch (error) {
    console.error('获取物料系数选项失败:', error)
  }
}

// 处理物料系数变化
const handleMaterialCoefficientChange = (value: number) => {
  form.materialCoefficient = value
  ElMessage.success('物料系数已更新，价格已重新计算')
}

// 计算单行总价 - 保持与calculateTotal一致的逻辑
const calculateRowTotalPrice = (row: any) => {
  const price = row.price || 0
  const priceTwo = row.priceTwo || 0
  const quantity = row.quantity || 0
  const additionalContent = row.additionalContent || 0
  const premium = row.premium || 0
  const premiumTwo = row.premiumTwo || 0
  const premiumThree = row.premiumThree || 0
  const premiumFour = row.premiumFour || 0
  
  // 计算公式：总价 = (单价1*数量+单价2*总层数)*(1+溢价1+溢价2+溢价3+溢价4)
  row.totalPrice = (price * quantity + priceTwo * additionalContent) * (1 + premium + premiumTwo + premiumThree + premiumFour)
  
  // 重新计算整体总金额
  calculateTotalAmount()
}

// 处理 additionalContent 变化
const handleAdditionalContentChange = (row: any, value: number) => {
  row.additionalContent = value || 0
  
  // 重新计算总价
  calculateRowTotalPrice(row)
}

// 计算整体总金额 - 由于使用了计算属性，这个方法主要用于触发响应式更新
const calculateTotalAmount = () => {
  // totalAmount 和 additionalTotalAmount 是计算属性，会自动重新计算
  // 更新表单总价为计算参考值
  form.totalPrice = totalAmount.value + additionalMaterialTotalAmount.value + additionalContentTotalAmount.value
}

// 计算参考总价（用于显示和自动填充）
const calculatedReferenceTotal = computed(() => {
  return totalAmount.value + additionalMaterialTotalAmount.value + additionalContentTotalAmount.value
})


// 页面初始化
onMounted(async () => {
  // 获取物料系数选项
  await getMaterialCoefficientOptions()
  
  // 检查是否有ID参数，如果有则是编辑模式
  if (route.params.id) {
    // 确保id是字符串或数字类型
    const id = Array.isArray(route.params.id)
        ? route.params.id[0]
        : route.params.id
    await getCostPlanDetail(id)
  }
  // 获取自定义物料模版
  //await getCostPlanTemplate(form.docType);
})

// 删除行
const removeRow = (index: number) => {
  // 删除表格中的数据，并返回
  const removedItem = form.costDetailList.splice(index, 1)[0];
  // 从已选物料中移除
  selectedMaterials.value = selectedMaterials.value.filter(
      (item) => item.id !== removedItem.costMaterialId)
}

// 数量是否可编辑
const isQuantityDisabled = (row: additionalTableData) => {
  if ( row.name === '输送机数'  || row.name === '复合输送数' || row.name === '输送机系数' || row.name === '电缆辅料' ||
    row.name === '电控盘' || row.name === 'HMI触摸屏' || row.name === 'HMI操作台' ||row.name === 'PLC' ||row.name === '分布式接口' || row.name === '图纸设计' || row.name === '程序设计'
    || row.name === '非标工艺占比' || row.name === '非常规环境'|| row.name === '配盘' || row.name === '安装' || row.name === '陪调' || row.name === '调试' || row.name === '陪产' || row.name === '现场安装' || row.name === '调试'
    || row.name === '陪产' || row.name === '陪调'|| row.name === '调试' || row.name === '现场安装' 
  ) {
    return true;
  } else {
    return false;
  }
}


// 单价1是否可编辑
const isPriceDisabled = (row: additionalTableData) => {
  if ( 
    row.name === 'PLC' 
  ) {
    return false;
  } else {
    return true;
  }
}

// 品牌是否可编辑
const isBrandDisabled = (row: additionalTableData) => {
  if (row.name === 'HMI触摸屏') {
    return false;
  } else {
    return true;
  }
}

// 高度是否可编辑
const isHeightDisabled = (row: additionalTableData) => {
  if (row.name === '提升机供电辅料' || row.name === '堆垛机供电辅料' 
  || row.name === '提升机供强电' || row.name === '提升机供弱电'
  || row.name === '堆垛机供强电' || row.name === '堆垛机供弱电'
  || row.name === 'RGV供电' || row.name === 'RGV供弱电') {
    return false;
  } else {
      return true;
  }
}

// 占比是否可编辑
const isRatioDisabled = (row: additionalTableData) => {
  if (row.name === '非标工艺占比' || row.name === '非常规环境') {
    return false;
  } else {
    return true;
  }
}

// 溢价是否可编辑
const isPremiumDisabled = (row: additionalTableData) => {
  if (row.name === 'HMI触摸屏') {
    return false;
  } else {
    return true;
  }
}


</script>

<template>
  <div class="electric-cost-sheet"
       v-loading="loading"
       element-loading-text="数据加载中..."
       element-loading-background="rgba(255, 255, 255, 0.7)">
    <!-- 顶部标题和操作区 -->
    <div class="header-container">
      <div class="header-left">
        <div class="title-area">
          <h1>{{ pageTitle }}</h1>
          <div class="subtitle">Electrical Control Cost Pricing Sheet</div>
        </div>
      </div>
      <div class="header-right">
        <el-button type="primary"
                   @click="saveForm"
                   :icon="Document"
                   v-if="!isViewMode">保存
        </el-button>
        <el-button type="success"
                   @click="getCostPlanTemplate(form.docType)"
                   :icon="Refresh"
                   :disabled="isViewMode">刷新</el-button>
        <el-button v-if="isViewMode"
                   @click="router.back()">返回</el-button>
      </div>
    </div>

    <!-- 表单信息区 -->
    <el-card class="form-info-card"
             shadow="hover">
      <div class="card-header">
        <div class="card-title">
          <el-icon>
            <Document />
          </el-icon>
          <span>基本信息</span>
        </div>
      </div>
      <el-form :model="form"
               label-position="top"
               :disabled="isViewMode"
               class="form-content">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="项目信息"
                          required>
              <el-input :model-value="selectedProject ? selectedProject.name : ''"
                        placeholder="请选择项目"
                        readonly
                        class="selector-input">
                <template #append>
                  <el-button @click="openProjectSelector" :disabled="isViewMode">选择</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据类型"
                          required>
              <el-select v-model="form.docType" filterable
                         @change="changeDocType"
                         placeholder="请选择单据类型"
                         class="full-width">
                <el-option label="输送系统"
                           value="输送系统" />
                <el-option label="提升机"
                           value="提升机" />
                <el-option label="堆垛机"
                           value="堆垛机" />
                           <el-option label="RGV"
                           value="RGV" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注">
              <el-input v-model="form.remark"
                        placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 操作按钮区 -->
    <div class="action-area">
      <div class="action-left">
        <div class="section-title">
          <el-icon><Select /></el-icon>
          <span>物料明细</span>
        </div>
      </div>
      <div class="action-right">
        <el-button type="primary"
                   @click="openMultipleSelectDialog"
                   :disabled="isViewMode">
          <el-icon>
            <Search />
          </el-icon>
          选择物料
        </el-button>
      </div>
    </div>

    <!-- 物料明细表格区 -->
    <el-card class="table-card"
             shadow="hover">
      <el-table :data="form.costDetailList"
                border
                stripe
                class="material-table"
                :header-cell-style="{background:'#f5f7fa',color:'#303133',fontWeight:'600'}"
                empty-text="暂无物料数据，请点击上方按钮添加物料">
        <el-table-column label="序号"
                         type="index"
                         width="60"
                         align="center" />
        <el-table-column label="材料名称"
                         min-width="180">
          <template #default="scope">
            <span class="material-name">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="型号规格"
                         min-width="180">
          <template #default="scope">
            <span>{{ scope.row.specification }}</span>
          </template>
        </el-table-column>
        <el-table-column label="品牌"
                         min-width="150">
          <template #default="scope">
            <span>{{ scope.row.brand }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单价"
                         width="130"
                         align="right">
          <template #default="scope">
            <span class="price-value">{{ scope.row.price ? `¥${scope.row.price.toFixed(2)}` : '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单价2"
                         width="130"
                         align="right">
          <template #default="scope">
            <span class="price-value">{{ scope.row.priceTwo ? `¥${scope.row.priceTwo.toFixed(2)}` : '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="溢价"
                         width="120"
                         align="right">
          <template #default="scope">
            <span class="premium-value">{{ scope.row.premium ? scope.row.premium.toFixed(2) : '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="溢价2"
                         width="120"
                         align="right">
          <template #default="scope">
            <span class="premium-value">{{ scope.row.premiumTwo ? scope.row.premiumTwo.toFixed(2) : '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="溢价3"
                         width="120"
                         align="right">
          <template #default="scope">
            <span class="premium-value">{{ scope.row.premiumThree ? scope.row.premiumThree.toFixed(2) : '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="溢价4"
                         width="120"
                         align="right">
          <template #default="scope">
            <span class="premium-value">{{ scope.row.premiumFour ? scope.row.premiumFour.toFixed(2) : '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数量"
                         width="120"
                         align="center">
          <template #default="scope">
            <el-input v-model="scope.row.quantity"
                             :min="0"
                             :step="0.1"
                             :precision="2"
                             size="small"
                             @change="() => updateQuantity(scope.row, scope.row.quantity)"
                             class="quantity-input" />
          </template>
        </el-table-column>
        <el-table-column label="总层数/接驳口"
                         width="120"
                         align="center">
          <template #default="scope">
            <el-input v-model="scope.row.additionalContent"
                             :min="0"
                             :step="0.1"
                             :precision="3"
                             size="small"
                             @change="() => handleAdditionalContentChange(scope.row, scope.row.additionalContent)"
                             class="quantity-input" />
          </template>
        </el-table-column>

        <el-table-column label="总价"
                         width="150"
                         align="right">
          <template #default="scope">
            <span class="total-price">{{ scope.row.totalPrice ? `¥${scope.row.totalPrice.toFixed(2)}` : '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作"
                         width="80"
                         align="center"
                         fixed="right">
          <template #default="scope">
            <el-button type="danger"
                       circle
                       size="small"
                       :icon="Delete"
                       :disabled="isViewMode"
                       @click="removeRow(scope.$index)" />
          </template>
        </el-table-column>
      </el-table>

      <!-- 表格底部汇总区 -->
      <div class="table-footer">
        <div class="total-section">
          <span class="total-label">物料总数:</span>
          <span class="total-value">{{ form.costDetailList.length }} 项</span>
        </div>
        <div class="total-section">
          <span class="total-label">基础金额:</span>
          <span class="total-value">¥{{ materialBaseAmount.toFixed(2) }}</span>
        </div>
        <div class="total-section">
          <span class="total-label">系数加成:</span>
          <div class="coefficient-selector">
            <el-select 
              v-model="form.materialCoefficient" 
              filterable
              placeholder="请选择系数加成"
              @change="handleMaterialCoefficientChange"
              style="width: 150px; margin-right: 8px;">
              <el-option 
                v-for="item in materialCoefficientOptions"
                :key="item.value"
                :label="`${item.label} (${item.value})`"
                :value="parseFloat(item.value)" />
            </el-select>
            <span v-if="form.materialCoefficient !== 1" class="coefficient-value">
              × {{ form.materialCoefficient }}
            </span>
          </div>
        </div>
        <div class="total-section">
          <span class="total-label">物料金额:</span>
          <span class="total-amount">¥{{ totalAmount.toFixed(2) }}</span>
        </div>
      </div>
    </el-card>

    <!-- 额外物料表格区 -->
    <div class="action-area"
         style="margin-top: 24px;">
      <div class="action-left">
        <div class="section-title">
          <el-icon>
            <Document />
          </el-icon>
          <span>额外物料</span>
        </div>
      </div>
    </div>

    <el-card class="table-card"
             shadow="hover">
      <el-table :data="additionalMaterialData"
                border
                stripe
                class="material-table"
                :header-cell-style="{background:'#f5f7fa',color:'#303133',fontWeight:'600'}"
                empty-text="暂无额外物料数据">
        <el-table-column label="序号"
                         type="index"
                         width="60"
                         align="center" />
        <el-table-column label="名称"
                         min-width="130">
          <template #default="scope">
            <el-input v-model="scope.row.name"
                      placeholder="请输入名称" disabled />
          </template>
        </el-table-column>
        <el-table-column label="规格型号"
                         min-width="120">
          <template #default="scope">
            <el-input v-model="scope.row.specification"
                      placeholder="请输入规格型号" disabled />
          </template>
        </el-table-column>
        <el-table-column label="品牌"
                         min-width="120">
          <template #default="scope">
            <el-input v-model="scope.row.brand"
                      :disabled="isBrandDisabled(scope.row)"
                      placeholder="请输入品牌"  />
          </template>
        </el-table-column>
        <el-table-column label="单价1"
                         width="100"
                         align="right">
          <template #default="scope">
            <el-input v-model="scope.row.price"
                             :min="0"
                             :precision="2"
                             :step="0.1"
                             @input="calculateAdditionalTotal(scope.row)"
                             :disabled="isPriceDisabled(scope.row)"

                             controls-position="right" />
          </template>
        </el-table-column>
        <el-table-column label="单价2"
                         width="100"
                         align="right">
          <template #default="scope">
            <el-input v-model="scope.row.priceTwo"
                             :min="0"
                             :precision="2"
                             :step="0.1"
                             @input="calculateAdditionalTotal(scope.row)"
                             controls-position="right" disabled />
          </template>
        </el-table-column>
        <el-table-column label="溢价"
                         width="80"
                         align="right">
          <template #default="scope">
            <el-input v-model="scope.row.premium"
                             :min="0"
                             :precision="2"
                             :step="0.01"
                             @input="calculateAdditionalTotal(scope.row)"
                             :disabled="isPremiumDisabled(scope.row)"
                             controls-position="right" />
          </template>
        </el-table-column>
        <el-table-column label="数量"
                         width="100"
                         align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.quantity"
                             :min="0"
                             :precision="2"
                             :step="0.01"
                             @change="() => calculateAdditionalTotal(scope.row)"
                             :disabled="isQuantityDisabled(scope.row)"
                             controls-position="right"
                             size="small" />
          </template>
        </el-table-column>
        <el-table-column label="总高度"
                         width="100"
                         align="right">
          <template #default="scope">
            <el-input v-model="scope.row.height"
                             :min="0"
                             :precision="2"
                             :step="0.1"
                             :disabled="isHeightDisabled(scope.row)"
                             controls-position="right" />
          </template>
        </el-table-column>
        <el-table-column label="总层数"
                         width="100"
                         align="right">
          <template #default="scope">
            <span>{{ scope.row.additionalContent || '--' }}</span>
          </template>
        </el-table-column>

        <el-table-column label="占比"
                         width="120"
                         align="right">
          <template #default="scope">
            <el-input v-model="scope.row.ratio"
                             :min="0"
                             :max="1"
                             :precision="2"
                             :step="0.01"
                             :disabled="isRatioDisabled(scope.row)"
                             @input="calculateAdditionalTotal(scope.row)"
                             controls-position="right" />
          </template>
        </el-table-column>
        <el-table-column label="合计"
                         width="150"
                         align="right">
          <template #default="scope">
            <span class="total-price">{{ scope.row.total ? `¥${scope.row.total.toFixed(2)}` : '¥0.00' }}</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 表格底部汇总区 -->
      <div class="table-footer">
        <div class="total-section">
          <span class="total-label">额外物料总数:</span>
          <span class="total-value">{{ additionalMaterialData.length }} 项</span>
        </div>
        <div class="total-section">
          <span class="total-label">基础金额:</span>
          <span class="total-value">¥{{ additionalMaterialBaseAmount.toFixed(2) }}</span>
        </div>
        <div class="total-section">
          <span class="total-label">系数:</span>
          <span class="coefficient-value">× {{ form.materialCoefficient }}</span>
        </div>
        <div class="total-section">
          <span class="total-label">额外物料金额:</span>
          <span class="total-amount">¥{{ additionalMaterialTotalAmount.toFixed(2) }}</span>
        </div>
      </div>
    </el-card>

    <!-- 额外内容表格区 -->
    <div class="action-area"
         style="margin-top: 24px;">
      <div class="action-left">
        <div class="section-title">
          <el-icon>
            <Document />
          </el-icon>
          <span>额外内容</span>
        </div>
      </div>
    </div>

    <el-card class="table-card"
             shadow="hover">
      <el-table :data="additionalContentData"
                border
                stripe
                class="material-table"
                :header-cell-style="{background:'#f5f7fa',color:'#303133',fontWeight:'600'}"
                empty-text="暂无额外内容数据">
        <el-table-column label="序号"
                         type="index"
                         width="60"
                         align="center" />
        <el-table-column label="名称"
                         min-width="130">
          <template #default="scope">
            <el-input v-model="scope.row.name"
                      placeholder="请输入名称" disabled />
          </template>
        </el-table-column>
        <el-table-column label="规格型号"
                         min-width="120">
          <template #default="scope">
            <el-input v-model="scope.row.specification"
                      placeholder="请输入规格型号" disabled />
          </template>
        </el-table-column>
        <el-table-column label="品牌"
                         min-width="120">
          <template #default="scope">
            <el-input v-model="scope.row.brand"
                      :disabled="isBrandDisabled(scope.row)"
                      placeholder="请输入品牌"  />
          </template>
        </el-table-column>
        <el-table-column label="单价1"
                         width="100"
                         align="right">
          <template #default="scope">
            <el-input v-model="scope.row.price"
                             :min="0"
                             :precision="2"
                             :step="0.1"
                             

                             @input="calculateAdditionalTotal(scope.row)"
                             controls-position="right" disabled />
          </template>
        </el-table-column>
        <el-table-column label="单价2"
                         width="100"
                         align="right">
          <template #default="scope">
            <el-input v-model="scope.row.priceTwo"
                             :min="0"
                             :precision="2"
                             :step="0.1"
                             @input="calculateAdditionalTotal(scope.row)"
                             controls-position="right" disabled />
          </template>
        </el-table-column>
        <el-table-column label="溢价"
                         width="80"
                         align="right">
          <template #default="scope">
            <el-input v-model="scope.row.premium"
                             :min="0"
                             :precision="2"
                             :step="0.01"
                             @input="calculateAdditionalTotal(scope.row)"
                             :disabled="isPremiumDisabled(scope.row)"
                             controls-position="right" />
          </template>
        </el-table-column>
        <el-table-column label="数量"
                         width="100"
                         align="center">
          <template #default="scope">
            <el-input v-model="scope.row.quantity"
                             :min="0"
                             :precision="2"
                             :step="0.01"
                             @change="() => calculateAdditionalTotal(scope.row)"
                             :disabled="isQuantityDisabled(scope.row)"
                             controls-position="right"
                             size="small" />
          </template>
        </el-table-column>
        <el-table-column label="总高度"
                         width="100"
                         align="right">
          <template #default="scope">
            <el-input v-model="scope.row.height"
                             :min="0"
                             :precision="2"
                             :step="0.1"
                             :disabled="isHeightDisabled(scope.row)"
                             controls-position="right" />
          </template>
        </el-table-column>
        <el-table-column label="占比"
                         width="120"
                         align="right">
          <template #default="scope">
            <el-input v-model="scope.row.ratio"
                             :min="0"
                             :max="1"
                             :precision="2"
                             :step="0.01"
                             :disabled="isRatioDisabled(scope.row)"
                             @input="calculateAdditionalTotal(scope.row)"
                             controls-position="right" />
          </template>
        </el-table-column>
        <el-table-column label="合计"
                         width="150"
                         align="right">
          <template #default="scope">
            <span class="total-price">{{ scope.row.total ? `¥${scope.row.total.toFixed(2)}` : '¥0.00' }}</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 表格底部汇总区 -->
      <div class="table-footer">
        <div class="total-section">
          <span class="total-label">额外内容总数:</span>
          <span class="total-value">{{ additionalContentData.length }} 项</span>
        </div>
        <div class="total-section">
          <span class="total-label">额外内容金额:</span>
          <span class="total-amount">¥{{ additionalContentTotalAmount.toFixed(2) }}</span>
        </div>
      </div>
    </el-card>

    <!-- 总价编辑区域 -->
    <el-card class="total-price-card" shadow="hover">
      <div class="card-header">
        <div class="card-title">
          <el-icon>
            <Document />
          </el-icon>
          <span>总价设置</span>
        </div>
      </div>
      
      <div class="total-price-content">
        <el-form :model="form" label-position="left" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="总价" required>
                <div style="display: flex; gap: 8px; align-items: center;">
                  <el-input 
                    v-model="form.totalPrice"
                    :min="0"
                    :precision="2"
                    :step="100"
                    placeholder="请输入总价"
                    controls-position="right"
                    size="large"
                    style="flex: 1;" />
                  <el-button 
                    type="primary" 
                    size="large"
                    @click="form.totalPrice = calculatedReferenceTotal"
                    :icon="Refresh">
                    使用计算值
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <div class="calculated-reference">
                <div class="reference-item">
                  <span class="reference-label">计算参考:</span>
                  <span class="reference-value">¥{{ calculatedReferenceTotal.toFixed(2) }}</span>
                </div>
                <div class="reference-item" v-if="form.totalPrice && Math.abs(form.totalPrice - calculatedReferenceTotal) > 0.01">
                  <span class="reference-label">差异:</span>
                  <span class="reference-value" :style="{ color: form.totalPrice > calculatedReferenceTotal ? '#67c23a' : '#f56c6c' }">
                    {{ form.totalPrice > calculatedReferenceTotal ? '+' : '' }}¥{{ (form.totalPrice - calculatedReferenceTotal).toFixed(2) }}
                  </span>
                </div>
                <div class="reference-note">
                  <span>物料金额: ¥{{ totalAmount.toFixed(2) }} (基础 ¥{{ materialBaseAmount.toFixed(2) }} × {{ form.materialCoefficient }})</span>
                  <span>额外物料: ¥{{ additionalMaterialTotalAmount.toFixed(2) }} (基础 ¥{{ additionalMaterialBaseAmount.toFixed(2) }} × {{ form.materialCoefficient }})</span>
                  <span>额外内容: ¥{{ additionalContentTotalAmount.toFixed(2) }}</span>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>

    <!-- 项目选择器组件 -->
    <ArchiveSelector v-model="projectSelectorVisible"
                     title="选择项目"
                     :search-fields="projectSearchFields"
                     :table-columns="projectTableColumns"
                     :fetch-data-api="getProjectList"
                     :multiple="false"
                     @confirm="handleProjectSelect" />

    <!-- 电控物料选择对话框 -->
    <ElectricalMaterialDialog ref="electricalMaterialDialogRef"
                              :multiple="isMultipleMode"
                              @handleMaterialSelectionChange="handleMaterialSelectionChange"
                              @confirmMaterialSelect="confirmMaterialSelect" />
  </div>
</template>

<style scoped lang="scss">
.electric-cost-sheet {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 100px);

  // 顶部标题和操作区
  .header-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .header-left {
      .title-area {
        h1 {
          font-size: 28px;
          font-weight: 700;
          color: #303133;
          margin: 0;
          background: linear-gradient(90deg, #409eff, #67c23a);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          letter-spacing: 2px;
        }

        .subtitle {
          font-size: 14px;
          color: #909399;
          margin-top: 4px;
          letter-spacing: 1px;
        }
      }
    }

    .header-right {
      display: flex;
      gap: 12px;

      .el-button {
        padding: 10px 20px;
        border-radius: 6px;
        font-weight: 500;
        transition: all 0.3s;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
      }
    }
  }

  // 表单信息卡片
  .form-info-card {
    margin-bottom: 24px;
    border-radius: 8px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
    border: none;
    overflow: hidden;

    .card-header {
      padding: 16px 20px;
      border-bottom: 1px solid #ebeef5;
      background: linear-gradient(90deg, #ecf5ff, #e6f7ff);

      .card-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 16px;
        font-weight: 600;
        color: #409eff;

        .el-icon {
          font-size: 18px;
        }
      }
    }

    .form-content {
      padding: 20px;

      :deep(.el-form-item__label) {
        font-weight: 500;
        color: #606266;
        padding-bottom: 4px;
      }

      :deep(.el-input__wrapper),
      :deep(.el-textarea__inner),
      :deep(.el-select__wrapper) {
        box-shadow: 0 0 0 1px #dcdfe6 inset;
        transition: all 0.3s;

        &:hover {
          box-shadow: 0 0 0 1px #c0c4cc inset;
        }

        &.is-focus {
          box-shadow: 0 0 0 1px #409eff inset;
        }
      }

      .full-width {
        width: 100%;
      }
    }
  }

  // 操作按钮区
  .action-area {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    .action-left {
      .section-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 18px;
        font-weight: 600;
        color: #303133;

        .el-icon {
          color: #409eff;
        }
      }
    }

    .action-right {
      display: flex;
      gap: 12px;

      .el-button {
        padding: 10px 16px;
        border-radius: 6px;
        transition: all 0.3s;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
      }
    }
  }

  // 表格卡片
  .table-card {
    border-radius: 8px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
    border: none;
    overflow: hidden;
    margin-bottom: 24px;

    .material-table {
      border-radius: 6px;
      overflow: hidden;

      :deep(.el-table__inner-wrapper) {
        border-radius: 6px;
      }

      .material-name {
        font-weight: 500;
        color: #303133;
      }

      .price-value {
        font-weight: 600;
        color: #409eff;
      }

      .premium-value {
        font-weight: 600;
        color: #e6a23c;
      }

      .total-price {
        font-weight: 600;
        color: #f56c6c;
      }

      .quantity-input {
        width: 100px;
      }
    }

    // 表格底部汇总区
    .table-footer {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      gap: 32px;
      padding: 16px 24px;
      background: #fafafa;
      border-top: 1px solid #ebeef5;

      .total-section {
        display: flex;
        align-items: center;
        gap: 8px;

        .total-label {
          font-size: 14px;
          color: #606266;
        }

        .total-value {
          font-size: 16px;
          font-weight: 600;
          color: #409eff;
        }

        .total-amount {
          font-size: 20px;
          font-weight: 700;
          color: #f56c6c;
        }

        .coefficient-selector {
          display: flex;
          align-items: center;
          gap: 8px;
        }

        .coefficient-value {
          font-size: 16px;
          font-weight: 600;
          color: #409eff;
        }
      }
    }

    // 表格操作区
    .table-actions {
      display: flex;
      justify-content: center;
      padding: 16px 0;
      border-top: 1px solid #ebeef5;

      .el-button {
        transition: all 0.3s;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
      }
    }
  }

  // 总价编辑卡片
  .total-price-card {
    border-radius: 8px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
    border: none;
    overflow: hidden;
    margin-bottom: 24px;

    .card-header {
      padding: 16px 20px;
      border-bottom: 1px solid #ebeef5;
      background: linear-gradient(90deg, #f0f9ff, #fef3c7);

      .card-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 16px;
        font-weight: 600;
        color: #1f2937;

        .el-icon {
          font-size: 18px;
          color: #f59e0b;
        }
      }
    }

    .total-price-content {
      padding: 24px;

      :deep(.el-form-item__label) {
        font-weight: 600;
        color: #374151;
        font-size: 16px;
      }

      :deep(.el-input-number__input) {
        font-size: 18px;
        font-weight: 600;
        color: #dc2626;
        text-align: center;
      }

      .calculated-reference {
        display: flex;
        flex-direction: column;
        justify-content: center;
        height: 100%;
        padding: 12px;
        background: #f8fafc;
        border-radius: 6px;
        border: 1px solid #e2e8f0;

        .reference-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;

          .reference-label {
            font-size: 14px;
            color: #64748b;
            font-weight: 500;
          }

          .reference-value {
            font-size: 18px;
            font-weight: 600;
            color: #059669;
          }
        }

        .reference-note {
          display: flex;
          flex-direction: column;
          gap: 4px;

          span {
            font-size: 12px;
            color: #94a3b8;
            font-weight: 400;
          }
        }
      }
    }
  }
}

// 响应式适配
@media (max-width: 1200px) {
  .electric-cost-sheet {
    padding: 16px;

    .header-container {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;

      .header-right {
        width: 100%;
        justify-content: flex-end;
      }
    }
  }
}

@media (max-width: 768px) {
  .electric-cost-sheet {
    padding: 12px;

    .header-container {
      .header-left {
        .title-area {
          h1 {
            font-size: 24px;
          }
        }
      }

      .header-right {
        flex-wrap: wrap;
        gap: 8px;

        .el-button {
          padding: 8px 12px;
        }
      }
    }

    .action-area {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;

      .action-right {
        width: 100%;
      }
    }

    .table-card {
      .table-footer {
        flex-direction: column;
        align-items: flex-end;
        gap: 8px;
      }
    }
  }
}
</style>
